package com.rslai.base.tool.servertest.database.postgresql;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.postgresql.util.PGobject;

public class PGHStore extends PGobject
        implements Serializable, Cloneable, Map {
    private static final long serialVersionUID = -5848774531402178123L;
    private Map _map;

    public PGHStore() {
        setType("hstore");
        this._map = new HashMap();
    }

    public PGHStore(String value)
            throws SQLException {
        this();
        setValue(value);
    }

    public PGHStore(Map map) {
        this();
        setValue(map);
    }

    public void setValue(Map map) {
        this._map = map;
    }

    public void setValue(String value)
            throws SQLException {
        Parser p = new Parser();
        this._map = p.parse(value);
    }

    public String getValue() {
        if (this._map == null) {
            return null;
        }
        StringBuffer buf = new StringBuffer();
        Iterator i = this._map.keySet().iterator();
        boolean first = true;
        while (i.hasNext()) {
            Object key = i.next();
            Object value = this._map.get(key);

            if (first)
                first = false;
            else {
                buf.append(',');
            }

            writeValue(buf, key);
            buf.append("=>");
            writeValue(buf, value);
        }

        return buf.toString();
    }

    private static void writeValue(StringBuffer buf, Object o) {
        if (o == null) {
            buf.append("NULL");
            return;
        }

        String s = o.toString();

        buf.append('"');
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if ((c == '"') || (c == '\\')) {
                buf.append('\\');
            }
            buf.append(c);
        }
        buf.append('"');
    }

    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof PGHStore)) {
            return false;
        }
        return this._map.equals(((PGHStore) obj)._map);
    }

    public void clear() {
        this._map.clear();
    }

    public boolean containsKey(Object key) {
        return this._map.containsKey(key);
    }

    public boolean containsValue(Object value) {
        return this._map.containsValue(value);
    }

    public Set entrySet() {
        return this._map.entrySet();
    }

    public Object get(Object key) {
        return this._map.get(key);
    }

    public int hashCode() {
        return this._map.hashCode();
    }

    public boolean isEmpty() {
        return this._map.isEmpty();
    }

    public Set keySet() {
        return this._map.keySet();
    }

    public Object put(Object key, Object value) {
        return this._map.put(key, value);
    }

    public void putAll(Map m) {
        this._map.putAll(m);
    }

    public Object remove(Object key) {
        return this._map.remove(key);
    }

    public int size() {
        return this._map.size();
    }

    public Collection values() {
        return this._map.values();
    }

    private static class Parser {
        private String value;
        private int ptr;
        private StringBuffer cur;
        private boolean escaped;
        private List keys;
        private List values;
        private static final int GV_WAITVAL = 0;
        private static final int GV_INVAL = 1;
        private static final int GV_INESCVAL = 2;
        private static final int GV_WAITESCIN = 3;
        private static final int GV_WAITESCESCIN = 4;
        private static final int WKEY = 0;
        private static final int WVAL = 1;
        private static final int WEQ = 2;
        private static final int WGT = 3;
        private static final int WDEL = 4;

        private Map parse(String value)
                throws SQLException {
            this.value = value;
            this.ptr = 0;
            this.keys = new ArrayList();
            this.values = new ArrayList();

            parseHStore();

            Map map = new HashMap();
            for (int i = 0; i < this.keys.size(); i++) {
                map.put(this.keys.get(i), this.values.get(i));
            }

            return map;
        }

        private boolean getValue(boolean ignoreEqual) throws SQLException {
            int state = 0;

            this.cur = new StringBuffer();
            this.escaped = false;
            while (true) {
                boolean atEnd = this.value.length() == this.ptr;
                char c = '\000';
                if (!atEnd) {
                    c = this.value.charAt(this.ptr);
                }

                if (state == 0) {
                    if (c == '"') {
                        this.escaped = true;
                        state = 2;
                    } else {
                        if (c == 0)
                            return false;
                        if ((c == '=') && (!ignoreEqual))
                            throw new SQLException("KJJ");
                        if (c == '\\') {
                            state = 3;
                        } else if (!Character.isWhitespace(c)) {
                            this.cur.append(c);
                            state = 1;
                        }
                    }
                } else if (state == 1) {
                    if (c == '\\') {
                        state = 3;
                    } else {
                        if ((c == '=') && (!ignoreEqual)) {
                            this.ptr -= 1;
                            return true;
                        }
                        if ((c == ',') && (ignoreEqual)) {
                            this.ptr -= 1;
                            return true;
                        }
                        if (Character.isWhitespace(c))
                            return true;
                        if (c == 0) {
                            this.ptr -= 1;
                            return true;
                        }
                        this.cur.append(c);
                    }
                } else if (state == 2) {
                    if (c == '\\') {
                        state = 4;
                    } else {
                        if (c == '"')
                            return true;
                        if (c == 0) {
                            throw new SQLException("KJJ, unexpected end of string");
                        }
                        this.cur.append(c);
                    }
                } else if (state == 3) {
                    if (c == 0) {
                        throw new SQLException("KJJ, unexpected end of string");
                    }

                    this.cur.append(c);
                    state = 1;
                } else if (state == 4) {
                    if (c == 0) {
                        throw new SQLException("KJJ, unexpected end of string");
                    }

                    this.cur.append(c);
                    state = 2;
                } else {
                    throw new SQLException("KJJ");
                }

                this.ptr += 1;
            }
        }

        private void parseHStore() throws SQLException {
            int state = 0;
            this.escaped = false;
            while (true) {
                char c = '\000';
                if (this.ptr < this.value.length()) {
                    c = this.value.charAt(this.ptr);
                }

                if (state == 0) {
                    if (!getValue(false)) {
                        return;
                    }
                    this.keys.add(this.cur.toString());
                    this.cur = null;
                    state = 2;
                } else if (state == 2) {
                    if (c == '=') {
                        state = 3;
                    } else {
                        if (state == 0)
                            throw new SQLException("KJJ, unexpected end of string");
                        if (!Character.isWhitespace(c))
                            throw new SQLException("KJJ, syntax err");
                    }
                } else if (state == 3) {
                    if (c == '>') {
                        state = 1;
                    } else {
                        if (c == 0) {
                            throw new SQLException("KJJ, unexpected end of string");
                        }
                        throw new SQLException("KJJ, syntax err [" + c + "] at " + this.ptr);
                    }
                } else if (state == 1) {
                    if (!getValue(true)) {
                        throw new SQLException("KJJ, unexpected end of string");
                    }

                    String val = this.cur.toString();
                    this.cur = null;
                    if ((!this.escaped) && ("null".equalsIgnoreCase(val))) {
                        val = null;
                    }

                    this.values.add(val);
                    state = 4;
                } else if (state == 4) {
                    if (c == ',') {
                        state = 0;
                    } else {
                        if (c == 0)
                            return;
                        if (!Character.isWhitespace(c))
                            throw new SQLException("KJJ, syntax err");
                    }
                } else {
                    throw new SQLException("KJJ unknown state");
                }

                this.ptr += 1;
            }
        }
    }
}
